<template>
  <div class="register-page">
    <div class="header">
      <img src="@/assets/logo.png" alt="logo" />
      <h1 class="title">团多多</h1>
    </div>
  
    <!-- 注册表单 -->
    <div class="register-form">
      <van-cell-group inset>
        <van-field v-model="registerForm.nickName" label="昵称" placeholder="昵称"
          :rules="[{ required: true, message: '请填写昵称' }]" />
        <van-field v-model="registerForm.email" label="邮箱" placeholder="邮箱"
          :rules="[{ pattern: emailPattern, message: '请输入正确的邮箱格式' }]" class="email-align">
          <template #button>
            <van-button size="small" type="primary" :disabled="codeButtonDisabled" @click="sendEmailCode">
              {{ codeButtonText }}
            </van-button>
          </template>
        </van-field>
        <!-- 图形验证码 -->
        <van-field v-model="checkCode.checkCode" label="图形验证码" placeholder="图形验证码">
          <template #button>
            <div class="captcha-container">
              <img v-if="captchaUrl" :src="captchaUrl" alt="图形验证码" @click="refreshCaptcha" class="captcha-image" />
            </div>
          </template>
        </van-field>
        <van-field v-model="registerForm.code" label="验证码" placeholder="邮箱验证码" />
        <van-field v-model="registerForm.password" type="password" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
        <van-field v-model="registerForm.birthday" label="生日" placeholder="请选择生日" is-link readonly
          @click="showDatePicker = true" />
      </van-cell-group>
    </div>
  
    <!-- 生日选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker v-model="currentDate" title="选择生日" :min-date="minDate" :max-date="maxDate" @confirm="onDateConfirm"
        @cancel="showDatePicker = false" />
    </van-popup>
  
    <!-- 注册按钮 -->
    <div class="submit-button">
      <van-button round block type="primary" @click="onRegister" color="#f40">
        注册
      </van-button>
    </div>
  
    <!-- 已有账号链接 -->
    <div class="login-link">
      <span class="login-text">已有账号？</span>
      <span class="login-action" @click="goToLogin">立即登录</span>
    </div>
  
    <!-- 协议说明 -->
    <div class="agreement">
      <van-checkbox v-model="agreed" checked-color="#f40">
        <span class="agreement-text">
          我已阅读并同意 <span class="link">用户协议</span> 和 <span class="link">隐私政策</span>
        </span>
      </van-checkbox>
    </div>
  </div>
</template>
  
  <script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import type { RegisterFormType, CheckCodeType } from '@/models/register/index'
import { getcheckCode } from '@/api/login'

// 路由
const router = useRouter()
// 表单数据
const registerForm = reactive<RegisterFormType>({
  nickName: '',
  email: '',
  code: '',
  password: '',
  birthday: ''
});

const checkCode = reactive<CheckCodeType>({
  email: '',
  checkCode: '',
  checkCodeKey: ''
});

// 验证正则
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

// 生日选择器相关
const showDatePicker = ref(false)
const currentDate = ref(['2000', '01', '01']) // 默认日期 [年, 月, 日]，使用字符串数组 // 默认日期 [年, 月, 日]
const minDate = new Date(1900, 0, 1)
const maxDate = new Date()

// 验证码倒计时相关
const codeCountdown = ref(0)
const codeTimer = ref<number | null>(null)

// 协议同意状态
const agreed = ref(false)

// 计算属性：验证码按钮状态
const codeButtonDisabled = computed(() => {
  return codeCountdown.value > 0 || !emailPattern.test(registerForm.email)
})

// 计算属性：验证码按钮文字
const codeButtonText = computed(() => {
  if (codeCountdown.value > 0) {
    return `${codeCountdown.value}秒后重发`
  }
  return '发送验证码'
})

const captchaUrl = ref<string>('')

// 获取图形验证码
const fetchCaptcha = async () => {
  // 这里应该替换为实际的API地址
  // 示例使用一个占位图片，实际项目中需要调用后端接口获取验证码
  const res = (await getcheckCode()).data
  checkCode.checkCodeKey = res.checkCodeKey
  captchaUrl.value = res.checkCode
}

// 刷新图形验证码
const refreshCaptcha = () => {
  fetchCaptcha()
}
import { getEmailCode } from '@/api/register'
// 发送邮箱验证码
const sendEmailCode = async () => {
  if (!emailPattern.test(registerForm.email)) {
    showToast({ message: '请输入正确的邮箱格式', type: 'fail' })
    return
  }
  checkCode.email = registerForm.email
  showToast({ message: '发送中...', type: 'loading' })
  getEmailCode(checkCode)
  setTimeout(() => {
    showToast({ message: '验证码已发送至您的邮箱', type: 'success' })

    // 启动倒计时
    codeCountdown.value = 60
    codeTimer.value = window.setInterval(() => {
      codeCountdown.value--
      if (codeCountdown.value <= 0 && codeTimer.value) {
        clearInterval(codeTimer.value)
        codeTimer.value = null
      }
    }, 1000)
  }, 1000)
}

// 日期确认
const onDateConfirm = ({ selectedValues }: { selectedValues: number[] }) => {
  const [year, month, day] = selectedValues
  registerForm.birthday = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
  showDatePicker.value = false
}

import { register } from '@/api/register'
// 注册处理
const onRegister = () => {
  // 表单验证
  if (!registerForm.nickName) {
    showToast({ message: '请输入昵称', type: 'fail' })
    return
  }

  if (!emailPattern.test(registerForm.email)) {
    showToast({ message: '请输入正确的邮箱格式', type: 'fail' })
    return
  }

  if (!registerForm.code) {
    showToast({ message: '请输入邮箱验证码', type: 'fail' })
    return
  }

  if (!registerForm.password) {
    showToast({ message: '请输入密码', type: 'fail' })
    return
  }

  if (!registerForm.birthday) {
    showToast({ message: '请选择生日', type: 'fail' })
    return
  }

  if (!agreed.value) {
    showToast({ message: '请先同意用户协议和隐私政策', type: 'fail' })
    return
  }

  // // 模拟注册请求
  showToast({ message: '注册中...', type: 'loading' })
  setTimeout(async () => {
    const result = await register(registerForm)
    console.log('注册信息:', result);
    showToast({ message: '注册成功', type: 'success' })
    console.log('注册信息:', registerForm)
    // 实际项目中这里应该跳转页面
    console.log('跳转到登录页')
    router.push('/login')
  }, 1500)


}

// 跳转到登录页
const goToLogin = () => {
  // 实际项目中这里应该使用路由跳转
  console.log('跳转到登录页')
  router.push('/login')
}

// 组件销毁时清理定时器
import { onUnmounted } from 'vue'
onUnmounted(() => {
  if (codeTimer.value) {
    clearInterval(codeTimer.value)
  }
})
// 组件挂载时获取验证码
onMounted(() => {
  fetchCaptcha()
})
  </script>
  
  <style scoped lang="scss">
.register-page {
    min-height: 100vh;
    background: #ffffff;
    padding-bottom: 40px;
  }
  
  .header {
    padding: 40px 20px 20px;
    text-align: center;
  }
  
  .title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 5px;
  }
  
  .subtitle {
    font-size: 14px;
    color: #666;
  }
  
  .register-form {
    padding: 20px 0;
  }
  
  .submit-button {
    margin: 30px 15px 0;
  }
  
  .login-link {
    text-align: center;
    margin: 20px 0;
  }
  
  .login-text {
    font-size: 14px;
    color: #666;
  }
  
  .login-action {
    font-size: 14px;
    color: #f40;
    margin-left: 5px;
    cursor: pointer;
  }
  
  .agreement {
    padding: 20px 15px 0;
  }
  
  .agreement-text {
    font-size: 12px;
    color: #666;
  }
  
  .link {
    color: #f40;
  }
  
  .captcha-container {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
  }
  
  .captcha-image {
    height: 25px;
    cursor: pointer;
    margin-left: 10px;
  }
  
  :deep(.van-cell-group) {
    .van-cell {
      margin-bottom: 15px;
  
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  
  .email-align {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
  }
</style>